package com.wbs.rest.config;


import com.wbs.rest.RestSqlController;
import com.wbs.rest.executor.JdbcSqlExecutor;
import com.wbs.rest.executor.SqlExecutor;
import com.wbs.rest.handler.AutoGenerateModelHandler;
import com.wbs.rest.model.JdbcSqlModelResolver;
import com.wbs.rest.model.SqlModelResolver;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.annotation.Resource;


@ComponentScan("com.wbs.rest.config")
@EnableConfigurationProperties({ SqlConfig.class})
public class SqlRestAutoBeanConfig {

    public static final String BASE_URI = "/{baseUri}";
    public static final String MAPPING_URI = "/{mappingUri}";
    public static final String MEDIA_TYPE = MediaType.APPLICATION_JSON_UTF8.toString();

    @Resource
    SqlConfig sqlConfig;

    @Resource
    JdbcTemplate jdbcTemplate;

    @Resource
    ApplicationContext applicationContext;

    @Bean
    public AutoGenerateModelHandler autoGenerateModelHandler(){
        return new AutoGenerateModelHandler();
    }

    @Bean
    @ConditionalOnMissingBean(SqlModelResolver.class)
    public SqlModelResolver sqlModelResolver(){
        return new JdbcSqlModelResolver(jdbcTemplate, sqlConfig);
    }

    @Bean
    @ConditionalOnMissingBean(SqlExecutor.class)
    public SqlExecutor sqlExecutor() {
        return new JdbcSqlExecutor(jdbcTemplate);
    }

    @Bean
    public SqlRestContext sqlRestContext(SqlConfig sqlConfig, SqlModelResolver sqlModelResolver, SqlExecutor sqlExecutor){
        SqlRestContext sqlRestContext = new SqlRestContext(sqlConfig, sqlModelResolver, sqlExecutor);
        sqlRestContext.initSqlModelHandler(applicationContext);
        return sqlRestContext;
    }

    @Bean
    public RestSqlController restSqlController(SqlModelResolver sqlModelResolver){
        return new RestSqlController(sqlModelResolver);
    }


}
